package com.me.web.server.netty.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * WebSocket 服务类
 *
 * @author chenlei
 */
@Slf4j
@Component
public class NettyWebSocketServer implements CommandLineRunner {

    /**
     * 端口号
     */
    private int port = 897;

    @Override
    public void run(String... args) {
        // 接收 WebSocket 连接的主 EventLoopGroup，用于处理接收新连接的请求
        EventLoopGroup webSocketBoss = new NioEventLoopGroup();
        // 处理 WebSocket 信息的从 EventLoopGroup，用于处理连接建立后的读写操作
        EventLoopGroup webSocketWorker = new NioEventLoopGroup();
        try {
            // 定义 WebSocket 服务器启动器
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(webSocketBoss, webSocketWorker)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            // 在通道的处理器链中添加 HttpServerCodec，用于处理 HTTP 协议的编解码
                            ch.pipeline().addLast(new HttpServerCodec());
                            // 添加 HttpObjectAggregator，用于将 HTTP 消息聚合成完整的请求或响应
                            ch.pipeline().addLast(new HttpObjectAggregator(65536));
                            // 添加 WebSocketServerProtocolHandler，用于处理 WebSocket 的握手、控制帧等
                            ch.pipeline().addLast(new WebSocketServerProtocolHandler("/websocket"));
                            // 添加自定义的处理器，用于处理 WebSocket 数据
                            ch.pipeline().addLast(new NettyWebSocketHandler());
                        }
                    });
            // 绑定端口
            ChannelFuture cf = serverBootstrap.bind(port).sync();
            // 优雅关闭连接
            cf.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("连接错误:{}", e.getMessage());
        } finally {
            webSocketBoss.shutdownGracefully();
            webSocketWorker.shutdownGracefully();
        }
    }
}

